# -*- coding: utf-8 -*-
"""
Windows Process Spy - 主启动器
GUI版本入口 - 终极tkinter环境解决方案
"""

import sys
import os

# 在导入任何其他模块之前，先设置Tcl/Tk环境
# 这是解决tkinter编译问题的关键步骤

def setup_tcltk_environment():
    """设置Tcl/Tk环境变量 - 必须在导入tkinter之前调用"""
    if sys.platform != 'win32':
        return
    if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
        tcl_path = os.path.join(sys._MEIPASS, 'tcl', 'tcl8.6')
        tk_path = os.path.join(sys._MEIPASS, 'tcl', 'tk8.6')
        if os.path.exists(tcl_path):
            os.environ['TCL_LIBRARY'] = tcl_path
            print(f"[OK] Set TCL_LIBRARY to: {tcl_path}")
        if os.path.exists(tk_path):
            os.environ['TK_LIBRARY'] = tk_path
            print(f"[OK] Set TK_LIBRARY to: {tk_path}")
        init_tcl = os.path.join(tcl_path, 'init.tcl')
        if os.path.exists(init_tcl):
            print(f"[OK] Found init.tcl: {init_tcl}")
        return
    possible_paths = [
        os.path.join(sys.prefix, 'tcl', 'tcl8.6'),
        os.path.join(sys.prefix, 'tcl', 'tk8.6'),
        os.path.join(sys.prefix, 'lib', 'tcl8.6'),
        os.path.join(sys.prefix, 'lib', 'tk8.6'),
    ]
    tcl_path = None
    tk_path = None
    for path in possible_paths:
        if 'tcl8.6' in path and os.path.exists(path):
            tcl_path = path
            break
    for path in possible_paths:
        if 'tk8.6' in path and os.path.exists(path):
            tk_path = path
            break
    if tcl_path:
        os.environ['TCL_LIBRARY'] = tcl_path
        print(f"[OK] Set TCL_LIBRARY to: {tcl_path}")
    else:
        print(f"[WARNING] TCL_LIBRARY not set")
    if tk_path:
        os.environ['TK_LIBRARY'] = tk_path
        print(f"[OK] Set TK_LIBRARY to: {tk_path}")
    else:
        print(f"[WARNING] TK_LIBRARY not set")
    if tcl_path:
        init_tcl = os.path.join(tcl_path, 'init.tcl')
        if os.path.exists(init_tcl):
            print(f"[OK] Found init.tcl: {init_tcl}")
        else:
            print(f"[WARNING] init.tcl not found in: {init_tcl}")

# 在导入任何其他模块之前设置Tcl/Tk环境
setup_tcltk_environment()

# 现在可以安全地导入其他模块
# 添加当前目录到路径
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
    sys.path.insert(0, current_dir)

# 导入全局tkinter环境设置
from modules.tkinter_setup import setup_tcltk_environment
setup_tcltk_environment()  # 确保环境变量设置

# 导入并运行GUI主程序
from modules.app.gui import main, debug_log

if __name__ == "__main__":
    try:
        debug_log("[START] WindowSpyGUI starting")
    except Exception:
        pass
    main()
